<template>
	<view class="">
		<template v-if="isWifi">
			<view class="find-header">
				<view class="find-header-img">
					<image mode="widthFix" src="https://statics.xmcsrv.net/weixin/wifi/connectWifi.png" alt=""/>
				</view>
				<view class="hint-text">
					如果你的Wi-Fi是 5GHz 的，请先设置为 2.4GHz
				</view>
			</view>
			<view class="" style="text-align: center;padding: 0 20rpx;">
				<uni-easyinput prefixIcon="tune" class="find-input" v-model="SSID" placeholder="请输入WIFI名称" @change="SSIDChange">
				</uni-easyinput>
				<uni-easyinput type="password" prefixIcon="locked" class="find-input" suffixIcon="eye" v-model="SSIDPwd"
					placeholder="请输入你的密码" @change="SSIDPwdChange"></uni-easyinput>
			</view>
			<view class="find-hint">
				*选择较强信号的WIFI，正确填写WIFI密码，可快速让设备联网
			</view>
			<view class="find-food">
				<view class="find-food-hint" @click="showConnectInfo">
					联网遇到问题？
				</view>
				<button class="find-food-submit" @tap="nextStep" type="default">下一步</button>
			</view>
		</template>
		<template v-else>
			<view class="u-f-ajc top">
				<image class="scanImg" src="https://statics.xmcsrv.net/weixin/searchBle.gif"></image>
				<view class="time">{{time}}'</view>
			</view>
			<template v-if="isLinked">
				<view class="find-success-hint">
					1.连接蓝牙设备成功！
				</view>
				<view v-if="isReceived" class="find-success-hint">
					2.设备已成功接收配网信息！
				</view>
				<view class="find-success-hint">{{isDistributeNet?'3.配网成功':'3.等待设备连接路由器...'}}</view>
			</template>
			<template v-else>
				<view class="find-success-hint">正在连接,请稍后...</view>
			</template>
			<view class="find-food">
				<button class="find-food-submit" data-code="601003" data-eventName="wifi_config_user_cancel" @tap="cancellink(1)">取消</button>
			</view>
		</template>
		<uni-popup ref="connectPopup">
			<view class="popup-connect" style="width: 600rpx;">
				<view class="popup-header">
					<text class="p-title">以下问题可能导致设备联网失败</text>
					<uni-icons class="close" type="closeempty" color="#AFAFAF" @click="closeConnectInfo"></uni-icons>
				</view>
				<view class="u-f-c popup-content">
					<text>1、检查是否开启WiFi防蹭网(此设置可能会导致设备无法正常联网)，可临时关闭，设备联网成功后再开启;</text>
					<text>2、如果您家是双频路由器，请检查摄像连接的WiFi是否是5GHz频段的WiFi，请切换连接2.4GHz频段的WiFi;</text>
					<text>3、如果您家的WiFi是桥接的(因为桥接的原因可能会导致网络不稳定)，建议连接非桥接WiFi;</text>
					<text>4、如果您的设备、路由器、手机，距离过远，或者中间有墙壁等障碍物，建议尽可能靠近</text>
				</view>
				<view class="popup-tips">温馨提示:选择较强信号的 WiFi，可快速让设备联网</view>
			</view>
		</uni-popup>
        <uni-popup  ref="popup" backgroundColor="#fff" :animation="false" :mask-click="false">
            <view class="popup-box">
                <view style="width: 100%;font-size: 14px;color: #FF0025;" v-if="!(popData.total>popData.params.limit*popData.params.page)">
                    <text @click="nextPage(-1)">上一页</text>
                </view>
                <view class="pop-title">
                    <text style="font-size: 16px; font-weight: 600;">{{ popData.title }}</text>
                </view>
                <view class="pop-content">
                    <view v-for="(item, index) in popData.data" class="pop-content-box" :key="index">
                        <view v-if="item.type == 0">
                            <text  :style="{fontSize: item.size+'px', color: item.color}">{{ item.content }}</text>
                        </view>
                        <view style="text-align: center" v-if="item.type == 1">
                            <img :src="item.content" style="width: 420rpx;height: 210rpx"></img>
                        </view>
                    </view>
                </view>
                <view class="pop-btn-box" v-if="popData.total>popData.params.limit*popData.params.page">
                    <button class="pop-btn" @click="nextPage(1)">下一页</button>
                </view>
                <view class="pop-btn-group" v-else>
                    <view style="width: 42%">
                        <button style="background-color: #f6f7fb;color: #000" @click="cancelBtn">取消</button>
                    </view>
                    <view style="width: 42%">
                        <button @click="againPost">重试</button>
                    </view>
                </view>
            </view>
        </uni-popup>
        <j-modal
            :showCancel="false"
            :value="alertDialog"
            okText="确定"
            title="提示"
            @ok="dialogConfirm"
            @mask="dialogConfirm"
        >
            <view slot="content">
                配网失败，请重新配网
            </view>
        </j-modal>
	</view>
</template>

<script>
	const {
		ab2hex,
		hexToString,
		hexStringToArrayBuffer,
		isSocket
	} = require('@/utils/util.js');
	const { strToHexCharCode } = require('@/jvss/pagesDevice/utils/index.js');
	export default {
		data() {
			return {
                alertDialog: false,
				isWifi:true,
				time: 180,
				timerId: null,
				isLinked: false,
				isDistributeNet: false,
				macAddress: '02:00:00:00:00:00', //'38:a9:1c:25:c3:c8',//'74-86-E2-0D-A3-59',
				macAddressDec: [],
				SSID: '',
				SSIDPwd: '',
				ipAddress: '',
				netmask: '',
				multicastTimer:null,
				broadcastTimer:null,
                popData: {},
                quickRC: {},
			}
		},
		onUnload() {
			console.log('关闭udp通信');
			this.udp.close()
			clearInterval(this.multicastTimer)
			clearInterval(this.broadcastTimer)
		},
		onLoad(opt) {
			let identifier = 'eeeeeeeeee' //配网标识符
			let gatewayStr = `gateway:'0.0.0.0'`
			let ipStr = `ip:${this.ipAddress}`
			let subwayStr = `subway:${this.netmask}`
			let dnsStr1 = 'dns1:0.0.0.0'
			let dnsStr2 = 'dns2:0.0.0.0'
			let macStr = `mac:${this.macAddress}`
			let randomID = `randomID:${Math.random()}`
			let str = identifier + gatewayStr + ' ' + ipStr + ' ' + subwayStr + ' ' + dnsStr1 + ' ' + dnsStr2 + ' ' +
				macStr + ' ' + randomID
			//let hexStr = strToHexCharCode(str)
			//let buffer = hexStringToArrayBuffer(hexStr)
			let sendbuffer = new ArrayBuffer(2048)
			let view = new Uint16Array(sendbuffer)
			for (let i = 0; i < str.length; i++) {
				view[i] = str.charCodeAt(i)
			}
			let buffer3 = new Uint16Array(172)
			console.log('发送udp', buffer3);
			let packageLen = this.concrete_package(buffer3)
            this.popData = JSON.parse(opt.netFailure)
            this.quickRC = JSON.parse(opt.quickResponseCode)
            console.log(this.popData, '传过来的参数popData')
            console.log(this.quickRC, '传过来的参数quickRC')
			// console.log('发送udp',packageLen,buffer3);
			// this.ipToInt(this.ipAddress)
			// this.setTime()
			// this.getIPAddress()
			this.startWifi()
			// this.dealWithMacAddress()
			this.dealwithSSIDPwd()
			this.dealwithSSIDContent()
		},
		onShow() {
			this.$postPointData({code:'601011', eventName:'click_wifi_config_button'})
			this.udp = wx.createUDPSocket()
			console.log('udp实例====',this.udp);
		},
		methods: {
            dialogConfirm() {
                this.alertDialog = false
                this.time = 180
                this.isWifi = true
            },
            againPost() {
                // 重试
                this.$refs.popup.close()
                this.isWifi = true
            },
            cancelBtn() {
                this.cancellink(1)
                this.$refs.popup.close()
            },
            // 下一页
            nextPage(num) {
                this.popData.params.page += num
                const {limit, page, pageId} = {...this.popData.params}
                const data = {
                    limit,
                    page,
                    pageId,
                }
                console.log(data, '传参变化')
                this.getDeviceGuideByPageId(data)
            },
            // 获取联网失败的信息
            getDeviceGuideByPageId(obj) {
                const {limit, page, pageId} = {...this.popData.params}
                console.log(obj)
                const data = obj ? obj : {limit, page, pageId}
                console.log(data)
                getApp().globalData.api.getDeviceGuideByPageId(data, res => {
                    console.log(res, '失败的数据123')
                    console.log(this.popData)
                    this.popData = {...this.popData, ...res}
                    console.log(this.popData, '12')
                    if(!obj) {
                        // this.popData.data = [...res.data]
                        // this.popData.total = res.total
                        this.$refs.popup.open()
                    }
                })
            },
			//获取IP地址
			getIPAddress() {
				wx.getLocalIPAddress({
					success: (res) => {
						const localip = res.localip
						this.ipAddress = res.localip
						this.netmask = res.netmask
						console.log('IP:---', res);
					}
				})
			},
			//wifi配网-----组播发消息
			udpSendMulticastData() {
				console.log('开始发送报文');
				let pwdAddress = []
				let pwdContent = this.dealwithSSIDPwd()
				let SSIDContent = this.dealwithSSIDContent()
				let pwdCRCList = this.crcCodeCalDisplacement(pwdContent)
				let ssidCRCList = this.crcCodeCalDisplacement(SSIDContent)

				console.log('macaddress=====', this.macAddressDec);
				console.log('pwdContent====', pwdContent);
				console.log('SSIDContent====', SSIDContent);
				console.log('pwdCRCList=====', pwdCRCList);
				console.log('ssidCRCList=====', ssidCRCList);

				const udp = this.udp
				let port = 1234
				let buffer = 'a'
				this.multicastTimer = setInterval(() => {
					// APP端的mac地址
					for (var i = 0; i < this.macAddressDec.length / 2; i++) {
						let m = this.macAddressDec[2 * i]
						let n = this.macAddressDec[2 * i + 1]
						this.udp.send({
							address: `226.${i}.${m}.${n}`,
							port: port,
							message: buffer
						})
					}
					// WiFi密码长度
					this.udp.send({
						address: `226.32.${this.SSIDPwd.length}.${this.SSIDPwd.length}`,
						port: port,
						message: buffer
					})
					// WiFi密码
					for (var i = 0; i < Math.ceil(pwdContent.length / 2); i++) {
						let m = pwdContent[2 * i]
						let n = pwdContent[2 * i + 1] ? pwdContent[2 * i + 1] : 0
						let str = `226.${64+i}.${n}.${m}`
						this.udp.send({
							address: str,
							port: port,
							message: buffer
						})
					}
					// WiFi密码CRC校验码
					for (var i = 0; i < pwdCRCList.length / 2; i++) {
						let m = pwdCRCList[2 * i + 1]
						let n = pwdCRCList[2 * i]
						this.udp.send({
							address: `226.${96+i}.${m}.${n}`,
							port: port,
							message: buffer
						})
					}
					// SSID（WIFI名称）长度
					this.udp.send({
						address: `226.16.${this.SSID.length}.${this.SSID.length}`,
						port: port,
						message: buffer
					})
					// SSID具体内容
					for (var i = 0; i < Math.ceil(this.SSID.length / 2); i++) {
						this.udp.send({
							address: `226.${48+i}.${(2*i+1)>=SSIDContent.length?0:SSIDContent[2*i+1]}.${SSIDContent[2*i]}`,
							port: port,
							message: buffer
						})
					}
					// SSID校验码
					for (var i = 0; i < ssidCRCList.length / 2; i++) {
						let m = ssidCRCList[2 * i + 1]
						let n = ssidCRCList[2 * i]
						this.udp.send({
							address: `226.${80+i}.${m}.${n}`,
							port: port,
							message: buffer
						})
					}
					// 移动端ip地址的最低字节
					let ipList = this.ipAddress.split('.')
					this.udp.send({
						address: `226.112.${ipList[ipList.length-1]}.${ipList[ipList.length-1]}`,
						port: port,
						message: buffer
					})
				}, 120)
				let info = {}
				//监听消息
				const bindPort = this.udp.bind(34571)
				// const bindPort = this.udp.bind()
				this.udp.onListening((res4)=>{
					console.log('监听组播中...',res4)
				})
				this.udp.onMessage((res) => {
					this.$postPointData({code:'601001', eventName:'start_wifi_config'})
					console.log('监听UDP消息', res);
					let hexStr = ab2hex(res.message)
					let jsonStr = hexToString(hexStr)
					console.log('dddddddd',hexStr);
					console.log('ddddddddjsonStr',jsonStr);
					let fotmatStr = jsonStr.replace(/\s*/g,"")
					let strArr = fotmatStr.split(',')
					
					console.log('strArr:===',strArr);
					strArr.forEach((item)=>{
						let ss = item.replace(/[\'\"\\\/\b\f\n\r\t]/g, '')
						if(item.includes('Pid')){
							info.pid = ss.split(':')[1]
						}
						if(item.includes('SN')){
							info.sn = ss.split(':')[1]
						}
						if(item.includes('DeviceType')){
							info.deviceType = ss.split(':')[1]
						}
					})
					console.log('dataInfo========',info,info.pid,Object.keys(info));
					if(Object.keys(info).length != 0){
						console.log('Object.keys(info)',Object.keys(info));
						let data = {
							pid: info.pid,
							deviceNo: info.sn,
							deviceType:info.deviceType
						}
						this.udp.close()
						let isVIot = isSocket().some(item=>item===info.pid)
						console.log('isViot',isVIot);
						let url = '/jvss/pagesDevice/device/qrcode/setpassword?device=' + encodeURIComponent(JSON.stringify(data))
						if(isVIot){
							url = `/jvss/pagesDevice/device/bluetooth/equipment-rename?device=${encodeURIComponent(JSON.stringify(data))}?connecttype=wifi`
						}
						// this.getAdminToken(data)
						uni.redirectTo({
							url:url
						});
						
					}
				})
			},
			// 获取设备最新的adminToken
			getAdminToken(json){
				let data = {
					deviceNo:json.deviceNo,
					isLatest:true
				}
				getApp().globalData.api.getDeviceTokenLocal(data, (result) => {
					// this.device.adminToken = result.adminToken
					console.log('获取最新token',result);
					this.$logs({info:'wifi配网成功获取adminToken',data:result})
					this.$postPointData({code:'601002'})
					result.pid = json.pid
					let url = ''
					if(result.adminToken){
						url = `/jvss/pagesDevice/device/bluetooth/equipment-rename?device=${encodeURIComponent(JSON.stringify(result))}?connecttype=wifi`
					}else{
						url = '/jvss/pagesDevice/device/qrcode/setpassword?device=' + encodeURIComponent(JSON.stringify(result))
					}
					uni.redirectTo({
						url:url
					});
				});
			},
			//wifi配网-----广播发消息
			udpSendBroadcasttData() {
				// const udp = wx.createUDPSocket()
				// let identifier = 'eeeeeeeeee' //配网标识符
				// let gatewayStr = `gateway:0.0.0.0`
				// let ipStr = `ip:${this.ipAddress}`
				// let subwayStr = `subway:${this.netmask}`
				// let dnsStr1 = 'dns1:0.0.0.0'
				// let dnsStr2 = 'dns2:0.0.0.0'
				// let macStr = `mac:${this.macAddress}`
				let identifier = 'eeeeeeeeee' //配网标识符
				let gatewayStr = `gateway:192.168.137.1`
				let ipStr = `ip:${this.ipAddress}`
				let subwayStr = `submask:${this.netmask}`
				let dnsStr1 = 'dns1:192.168.137.1'
				let dnsStr2 = 'dns2:0.0.0.0'
				let macStr = `mac:4C:49:E3:1F:54:93`
				let randomID = `randomID:${Math.random()}`
				let str = identifier + gatewayStr + ' ' + ipStr + ' ' + subwayStr + ' ' + dnsStr1 + ' ' + dnsStr2 + ' ' + macStr + ' ' + randomID
				//let hexStr = strToHexCharCode(str)
				//let buffer = hexStringToArrayBuffer(hexStr)
				let sendbuffer = new ArrayBuffer(2048)
				// let view = new Uint16Array(sendbuffer)
				// for (let i = 0; i < str.length; i++) {
				// 	view[i] = str.charCodeAt(i)
				// }

				let dataView = new DataView(sendbuffer);
				for (var i = 0; i < str.length; i++) {
					var curCharCode = parseInt(str.substr(i * 2, 2), 16);
					dataView.setUint8(i, str.charCodeAt(i));
				}
				console.log('发送广播数据Str', str);
				console.log('发送广播数据buffer', sendbuffer);
				// console.log('发送广播数据hexStr',hexStr);

				let port = 8001
				let buffer3 = new Uint16Array(172)
				let packageLen = this.concrete_package(buffer3)
				console.log('发送udp', packageLen, buffer3);
				this.broadcastTimer = setInterval(() => {
					console.log('发送udp=====');
					this.udp.send({
						address: '255.255.255.255',
						port: port,
						message: sendbuffer,
						length: 500,
						setBroadcast: true
					})
					for (var i = 0; i < packageLen; i++) {
						this.udp.send({
							address: '255.255.255.255',
							port: port,
							message: sendbuffer,
							length: buffer3[i],
							setBroadcast: true
						})
					}
				}, 500)
				this.udp.bind(34571)
				// this.udp.bind()
				// this.udp.bind(45149)
				this.udp.onListening((res4)=>{
					console.log('监听广播中...',res4)
				})
				this.udp.onMessage((res) => {
					console.log('监听广播收到的消息', res);
					let hexStr = ab2hex(res.message)
					let str = hexToString(hexStr)
					console.log('监听广播收到的消息hex', hexStr);
					console.log('监听广播收到的消息str', str);
				})

			},
			// 广播数据包长
			concrete_package(buffer) {
				let wifiInfo = {
					ssid: this.SSID,
					password: this.SSIDPwd,
					ipAddress: this.ipAddress
				}
				let encPwd = this.dealwithSSIDPwd()
				let ipInt = this.ipToInt(this.ipAddress)
				let pwdAscii = wifiInfo.password
				let SYNC_FRAME_LEN = 1300
				let i, j, total_len, flag, ssid_len, passwd_len, integer_len, remainder_len;
				let unpacked_index;
				let realdata = new ArrayBuffer(512);
				let cal_crc;
				let outbuf2send = new Uint16Array(172)
				let offset;
				//outbuf[0] = outbuf[1] = outbuf[2] = SYNC_FRAME_LEN;
				ssid_len = wifiInfo.ssid.length;
				passwd_len = wifiInfo.password.length;
				total_len = 6 + ssid_len + passwd_len + 1;
				flag = 0x41; //表示有ssid  并且有ip地址
				integer_len = parseInt((total_len / 3) * 3);
				remainder_len = (total_len % 3);
				console.log('total_len', ssid_len, passwd_len, total_len, remainder_len);
				//------------实际发包数据---------
				j = 0;
				realdata[j++] = total_len;
				realdata[j++] = flag;
				realdata[j++] = ssid_len;
				realdata[j++] = passwd_len;
				for (i = 0; i < ssid_len; i++) {
					realdata[j++] = wifiInfo.ssid.charCodeAt(i); // 拿ssid字符每位的acsii
					// console.log('拿ssid字符每位的acsii',wifiInfo.ssid.charCodeAt(i));
				}
				for (i = 0; i < passwd_len; i++) {
					realdata[j++] = encPwd[i]; // 拿加过密的密码每个位的acsii
					// console.log('加过密的密码每个位的acsii',encPwd[i]);
				}
				realdata[j++] = (ipInt >> 24) & 0xFF; // zbd-150723    
				cal_crc = 0;
				for (i = 0; i < j; i++) {
					cal_crc += realdata[i];
				}
				realdata[j++] = cal_crc & 0xFF;
				realdata[j++] = (cal_crc >> 8) & 0xFF;


				// console.log(": ",);
				//----------------------------------------
				offset = 0;
				for (i = 0; i < integer_len; i += 3) {
					unpacked_index = parseInt(i * 8 / 3);
					if (unpacked_index == 32) {
						offset += 3;

						outbuf2send[unpacked_index] = SYNC_FRAME_LEN + 1;
						outbuf2send[unpacked_index + 1] = SYNC_FRAME_LEN + 1;
						outbuf2send[unpacked_index + 2] = SYNC_FRAME_LEN + 1;
					}
					outbuf2send[offset + unpacked_index] = (realdata[i] & 0x07) | ((unpacked_index + 16) << 3);
					outbuf2send[offset + unpacked_index + 1] = ((realdata[i] >> 3) & 0x07) | ((unpacked_index + 16 + 1) <<
						3);
					outbuf2send[offset + unpacked_index + 2] = ((realdata[i] >> 6) & 0x03) | ((unpacked_index + 16 + 2) <<
						3);
					outbuf2send[offset + unpacked_index + 2] |= (realdata[i + 1] << 2) & 0x04;
					outbuf2send[offset + unpacked_index + 3] = ((realdata[i + 1] >> 1) & 0x07) | ((unpacked_index + 16 +
						3) << 3);
					outbuf2send[offset + unpacked_index + 4] = ((realdata[i + 1] >> 4) & 0x07) | ((unpacked_index + 16 +
						4) << 3);
					outbuf2send[offset + unpacked_index + 5] = ((realdata[i + 1] >> 7) & 0x01) | (unpacked_index + 16 +
						5 << 3);
					outbuf2send[offset + unpacked_index + 5] |= (realdata[i + 2] << 1) & 0x06;
					outbuf2send[offset + unpacked_index + 6] = ((realdata[i + 2] >> 2) & 0x07) | (unpacked_index + 16 +
						6 << 3);
					outbuf2send[offset + unpacked_index + 7] = ((realdata[i + 2] >> 5) & 0x07) | (unpacked_index + 16 +
						7 << 3);
					// console.log('数据包长outbuf2send======',outbuf2send);
				}
				if (remainder_len) {
					unpacked_index = parseInt(i * 8 / 3);
					outbuf2send[offset + unpacked_index] = (realdata[i] & 0x07) | (unpacked_index + 16 << 3);
					outbuf2send[offset + unpacked_index + 1] = ((realdata[i] >> 3) & 0x07) | (unpacked_index + 16 + 1 <<
						3);
					outbuf2send[offset + unpacked_index + 2] = ((realdata[i] >> 6) & 0x03) | (unpacked_index + 16 + 2 <<
						3);
					if (remainder_len > 1) {
						outbuf2send[offset + unpacked_index + 2] |= (realdata[i + 1] << 2) & 0x04;
						outbuf2send[offset + unpacked_index + 3] = ((realdata[i + 1] >> 1) & 0x07) | (unpacked_index + 16 +
							3 << 3);
						outbuf2send[offset + unpacked_index + 4] = ((realdata[i + 1] >> 4) & 0x07) | (unpacked_index + 16 +
							4 << 3);
						outbuf2send[offset + unpacked_index + 5] = ((realdata[i + 1] >> 7) & 0x01) | (unpacked_index + 16 +
							5 << 3);
					}
				}
				console.log('remainder_len', remainder_len);
				console.log('unpacked_index', unpacked_index);
				console.log('offset', offset);
				unpacked_index = parseInt(offset + 3 + (total_len * 8 + 2) / 3);
				// outbuf2send.slice(SYNC_FRAME_LEN,SYNC_FRAME_LEN,SYNC_FRAME_LEN)
				// let resultbuffer = new Uint16Array(172)
				/////while 循环
				buffer[0] = buffer[1] = buffer[2] = 1300
				console.log('unpacked_index', unpacked_index);
				// var x = 0;x<unpacked_index;x++
				for (var x = 0; x < unpacked_index + 2 + offset; x++) {
					buffer[x + 3] = outbuf2send[x];
				}
				// for(var x = 0;x<unpacked_index;x++){
				// 	buffer[x+3] = outbuf2send[x];
				// }
				console.log('buffer==========', buffer, buffer.length);
				console.log('outbuf2send====', outbuf2send, outbuf2send.length);
				// console.log('buffer22222=======',resultbuffer);
				return  unpacked_index + 2 + offset;

			},

			ipToInt(ip_str) {
				const type = Object.prototype.toString.call(ip_str)
				if (type !== '[object Array]') {
					ip_str = ip_str.split('.')
				}
				if (ip_str.length !== 4) return 0
				ip_str = ip_str.map(i => Number(i))
				if (ip_str.find(i => i < 0 || i > 255)) return 0
				const t = (prev, cur) => prev * Number(1 << 8) + cur
				console.log('IP转Int', ip_str.reduce(t, Number(0)));
				return ip_str.reduce(t, Number(0))
			},
			// mac地址进行处理
			dealWithMacAddress() {
				let mac = this.macAddress.split(':')
				mac.forEach((item) => {
					this.macAddressDec.push(this.hexToDec(item))
				})
				console.log("this.macAddressDec: ", this.macAddressDec);
				this.getIPAddress()
			},
			// SSIDPwd密码进行处理
			dealwithSSIDPwd() {
				let pwdListAddress = []
				for (var i = 0; i < this.SSIDPwd.length; i++) {
					let item = this.SSIDPwd.charCodeAt(i)
					// let asciiStr = String(item).charCodeAt()
					let res = item ^ (0x50 + i)
					// console.log('异或运算====',res,item,i);
					pwdListAddress.push(res)
				}
				// console.log('异或运算密码',pwdListAddress);
				return pwdListAddress
			},
			// SSID内容进行处理
			dealwithSSIDContent() {
				let SSIDAddress = []
				for (var i = 0; i < this.SSID.length; i++) {
					let item = this.SSID[i]
					let asciiStr = String(item).charCodeAt()
					SSIDAddress.push(asciiStr)
				}
				return SSIDAddress
			},
			//转ASCII码  CRC校验之前 先对内容进行异或运算后转ASCII码 再进行CRC校验
			dealwithContentToASCII(content) {
				let asciiArr = []
				// let pwdList = this.dealwithSSIDPwd()
				for (var i = 0; i < content.length; i++) {
					asciiArr.push(String.fromCharCode(content[i]))
				}
				let str = asciiArr.join('')
				let res = this.crc32str(0, str, str.length, 0)
				return res
			},
			// 对计算出来的CRC校验码 进行位移之后转16进制 再&ff
			crcCodeCalDisplacement(content) {
				let str = this.dealwithContentToASCII(content)
				let pwdCRCRes = []
				for (var i = 0; i < 2; i++) {
					let m = ((str >> (2 * i + 0) * 8)) & 0xff
					let n = ((str >> (2 * i + 1) * 8)) & 0xff
					pwdCRCRes.push(m, n)
					// console.log('来的CRC校验码 进行位移之后',m,'===',n);
				}
				console.log('算出来的CRC校验码', pwdCRCRes);
				return pwdCRCRes
			},
			// 列出单元可能的情况2^8和h`的结果
			makeTable() {
				var c, table = [];
				for (var n = 0; n < 256; n++) {
					c = n;
					for (var k = 0; k < 8; k++) {
						c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
					}
					table[n] = c;
				}
				return table;
			},
			//CRC校验
			crc32str(crc, str, len, pos) {
				var crcTable = this.makeTable();
				var t = crcTable,
					end = pos + len;
				crc = crc ^ (-1);
				for (var i = pos; i < end; i++) {
					crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
				}
				console.log('CRC校验====', (crc ^ (-1)));
				return (crc ^ (-1)); // >>> 0;
			},
			// 16进制转10进制
			hexToDec(hex) {
				// 传入"B7 D4", 翻转去除空格"4D7B", 结果19835
				// let str = hex.split('').reverse().join('');
				let str = hex.split('').join('')
				let decimalism = str.replace(/\s/g, "");
				let res = parseInt(decimalism, 16)
				// console.log("16转10的值: ", res);//十六进制转十进制
				return res
			},
			//初始化 Wi-Fi 模块
			startWifi() {
				wx.startWifi({
					success: (res) => {
						// this.onWifiConnect()
						this.getConnectedWifi()
					},
					fail: (err) => {
						console.log('wifierr:', err);
					}
				})
			},
			//获取WiFi信息
			getConnectedWifi() {
				let that = this
				wx.getConnectedWifi({
					partialInfo: false,
					success: res => {
						console.log('获取WIFI信息=====', res)
						that.SSID = res.wifi.SSID
						that.macAddress = res.wifi.BSSID
						if (!res.wifi.BBSID) {
							// that.macAddress = '02:00:00:00:00:00'
						}
						console.log('WIFI信息BBSI======',res.wifi.BBSID);
						console.log('macAddress', that.macAddress);
						that.dealWithMacAddress()
					}
				})
			},
			// 设置倒计时
			setTime() {
				this.timerId = setInterval(() => {
					this.time = this.time - 1
					if (this.time < 1) {
						clearInterval(this.timerId)
                        if(Object.keys(this.popData).length) {
                            this.getDeviceGuideByPageId()
                            this.cancellink()
                            return
                        }
                        // 超时
                        this.alertDialog = true
                        // this.cancellink(1)
                        uni.hideLoading()
                        this.udp.close()
                        clearInterval(this.timerId)
                        clearInterval(this.multicastTimer)
                        clearInterval(this.broadcastTimer)
					}
				}, 1000)
			},
			//输入WiFi信息
			SSIDChange(e){
				// this.dealwithSSIDContent()
			},
			SSIDPwdChange(e){
				// this.dealwithSSIDPwd()
			},
			//取消配网
			cancellink(status) {
                if(status) {
                    this.isWifi = true
                }
				clearInterval(this.timerId)
				this.time = 180
				uni.hideLoading()
				this.udp.close()
				clearInterval(this.multicastTimer)
				clearInterval(this.broadcastTimer)
				// uni.navigateBack({})
			},
			//下一步
			nextStep(){
                if(Object.keys(this.quickRC).length !== 0) {
                    console.log(this.quickRC, '这是powered页面传过来的quickResponseCode')
                    const device = {
                        wifiName: this.SSID,
                        wifiPwd: this.SSIDPwd
                    }
                    uni.navigateTo({
                        url: '/jvss/pagesDevice/device/qrcode/codeprompt?quickRC=' + JSON.stringify(this.quickRC) + '&device=' + JSON.stringify(device)
                    })
                    return
                }
                console.log(this.quickRC, '这是powered页面传过来的quickResponseCode222')
				if(!this.SSID||!this.SSIDPwd){
					uni.showToast({
						title:'请将wifi信息请输入完整',
						icon:'none'
					})
					return
				}
				this.dealwithSSIDContent()
				this.dealwithSSIDPwd()
				setTimeout(()=>{
					this.udpSendMulticastData()  //组播
					// this.udpSendBroadcasttData() //广播
				},500)
				uni.showLoading({
					mask:true
				})
				setTimeout(()=>{
					this.isWifi = false
					this.setTime();
					uni.hideLoading()
				},500);
			},
			//联网遇到的问题弹框
			showConnectInfo(){
				this.$refs.connectPopup.open();
			},
			closeConnectInfo(){
				this.$refs.connectPopup.close();
			},

		}
	}
</script>

<style lang="scss" scoped>
	/deep/.uniui-eye-slash-filled:before {
		content: "\e66a";
	}
	/deep/.uniui-eye-filled:before {
	    content: "\e6b4";
	}
	/deep/ .uni-easyinput{
		margin-top: 20rpx;
	}
	.top {
		position: relative;
		margin: 100rpx 0;

		.scanImg {
			width: 300rpx;
			height: 300rpx;
		}

		.time {
			font-size: 30rpx;
			font-weight: 700;
			color: white;
			z-index: 9;
			position: absolute;
			left: 0;
			right: 0;
			text-align: center
		}
	}
	.find-header {
		margin-bottom: 50rpx;
	}
	
	.find-header-img {
		// width: 100px;
		// height: 100px;
		// margin: auto;
		margin-top: 60px;
		margin-bottom: 30px;
		text-align: center;
	}
	
	.find-header-img image {
		width: 400rpx;
	}
	.hint-text{
		font-size: 22rpx;
		color: #444444;
		line-height: 29rpx;
		text-align: center;
	}
	.find-type {
		display: flex;
		justify-content: center;
		font-size: 30rpx;
	
	}
	
	.find-type-t {
		color: #FF0025;
		margin-right: 20rpx;
	}
	
	.find-type-f {
		color: #F8716B;
	}

	.find-type-icons {
		text-align: center;
	}
	.find-hint {
		font-size: 16rpx;
		line-height: 15px;
		color: #444444;
		opacity: 0.8;
		margin-left: 2%;
	}
	
	.uni-easyinput {
		width: 96% !important;
		height: 80rpx;
		background: #fff;
		border-radius: 16rpx;
		margin: 20rpx auto;
	}
	
	.uni-easyinput .is-input-border {
		border: none;
	}

	.find-success-hint {
		font-size: 28rpx;
		color: #707070;
		text-align: center;
	}

	.find-food {
		text-align: center;
		position: fixed;
		bottom: 30rpx;
		width: 100%;
		font-size: 28rpx;
	}
	.find-food-hint {
		color: #FF0025;
		margin-bottom: 40rpx;
	}

	.find-food-submit {
		border: 1px solid #B9B9B9;
		border-radius: 16rpx;
		background-color: #fff;
		color: #FF0025 !important;
		width: 96%;
		height: 80rpx;
		line-height: 80rpx;
		margin-top: 50rpx;
	}
	.popup-connect{
		background-color: #fff;
		// padding: 20rpx;
		border-radius: 10rpx;
		text-align: center;
	}
	.popup-header{
		position: relative;
		border-bottom: 1rpx solid #EEEEEE;
		padding: 20rpx;
		.p-title{
			font-size: 26rpx;
		}
		.close{
			position: absolute;
			right: 10rpx;
			top: 30rpx;
		}
	}
	.popup-content{
		padding: 30rpx;
		height: 380rpx;
		overflow: scroll;
		text-align: left;
		text{
			margin-top: 20rpx;
			color: #AFAFAF;
			font-size: 24rpx;
		}
	}
	.popup-tips{
		border-top: 1rpx solid #EEEEEE;
		padding: 20rpx;
		color: #FF0025;
		font-size: 26rpx;
		text-align: center;
	}
	
	.popup-button button {
		width: 200rpx !important;
		height: 80rpx;
		border-radius: 40px;
		border: none;
		font-size: 30rpx;
	}
    /deep/ .uni-popup__wrapper {
        border-radius: 10px;
        //max-height: 581px;
        //min-height: 491px;
    }
    .popup-box {
        width: 540rpx;
        //height: 980rpx;
        height: 100%;
        display: flex;
        padding: 32rpx 20rpx 32rpx 26rpx;
        border-radius: 10px;
        box-sizing: border-box;
        flex-direction: column;
        justify-content: start;
        align-items: center;
        .pop-title {
            margin-bottom: 30rpx;
        }
        .pop-content-box {
            margin-bottom: 16rpx;
        }
        .pop-btn-box {
            width: 90%;
            margin-top: 40rpx;
            button {
                height: 35px;
                line-height: 35px;
                font-size: 16px;
                color: #fff;
                border-radius: 20px;
                background-color: #FF0025;
            }
        }
        .pop-btn-group {
            width: 90%;
            margin-top: 40rpx;
            display: flex;
            justify-content: space-between;
            button {
                height: 35px;
                line-height: 35px;
                font-size: 16px;
                color: #fff;
                border-radius: 20px;
                background-color: #FF0025;
            }
        }
    }
</style>
